package v3;

import cn.hutool.core.util.StrUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

public class WiFiManager {

    public WiFiConnectionResult connectToWiFi(String ssid, String password) {
        WiFiConnectionResult result = new WiFiConnectionResult();
        result.setSsid(ssid);

        try {
            // 使用nmcli连接WiFi
            ProcessBuilder pb = new ProcessBuilder(
                    "nmcli", "device", "wifi", "connect", ssid, "password", password
            );

            Process process = pb.start();
            boolean finished = process.waitFor(30, TimeUnit.SECONDS);

            if (finished) {
                int exitCode = process.exitValue();
                if (exitCode == 0) {
                    result.setSuccess(true);
                    result.setMessage("WiFi连接成功");
                } else {
                    result.setSuccess(false);

                    // 读取错误信息
                    BufferedReader errorReader = new BufferedReader(
                            new InputStreamReader(process.getErrorStream()));
                    StringBuilder error = new StringBuilder();
                    String line;
                    while ((line = errorReader.readLine()) != null) {
                        error.append(line);
                    }
                    result.setMessage("WiFi连接失败: " + error.toString());
                }
            } else {
                result.setSuccess(false);
                result.setMessage("WiFi连接超时");
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("WiFi连接异常: " + e.getMessage());
        }

        return result;
    }

    public String checkWiFiConnectionStatus(String targetSSID) {

        try {
            // 执行nmcli命令，获取活跃状态和SSID
            ProcessBuilder pb = new ProcessBuilder("nmcli", "-t", "-f", "ACTIVE,SSID", "dev", "wifi");
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) {
                    continue;
                }

                // 分割ACTIVE和SSID（格式："yes:WiFi名称" 或 "no:WiFi名称"）
                String[] parts = line.split(":", 2); // 最多分割为两部分
                if (parts.length < 2) {
                    continue;
                }

                String activeStatus = parts[0].toLowerCase();
                String currentSSID = parts[1];

                // 匹配目标SSID，且状态为活跃（连接中）
                if ((StrUtil.isBlank(targetSSID) || currentSSID.equals(targetSSID)) &&
                        (activeStatus.equals("yes") || activeStatus.equals("是"))) {
                    return "Connected";
                }
            }

            // 等待进程结束，避免资源泄露
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 未找到目标Wi-Fi或未连接，返回Disconnected
        return "Disconnected";
    }

    public static class WiFiConnectionResult {
        private boolean success;
        private String message;
        private String ssid;
        private String errorDetails;

        // Getters and Setters
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }

        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }

        public String getSsid() { return ssid; }
        public void setSsid(String ssid) { this.ssid = ssid; }

        public String getErrorDetails() { return errorDetails; }
        public void setErrorDetails(String errorDetails) { this.errorDetails = errorDetails; }
    }
}
